package com.sunwayworld.basemodule.common.eptstorage.db.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.common.eptstorage.db.bean.LimsDbconnBean;
import com.sunwayworld.basemodule.common.eptstorage.db.bean.LimsDbextractConfigBean;
import com.sunwayworld.basemodule.common.eptstorage.db.dao.LimsDbconnDao;
import com.sunwayworld.basemodule.common.eptstorage.db.service.LimsDbconnService;
import com.sunwayworld.basemodule.common.eptstorage.db.service.LimsDbextractConfigService;
import com.sunwayworld.basemodule.common.eptstorage.db.DbHelper;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.ObjectUtils;
import com.sunwayworld.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
@GikamBean
public class LimsDbconnServiceImpl implements LimsDbconnService {

    @Autowired
    private LimsDbconnDao limsDbconnDao;
    @Autowired
    private LimsDbextractConfigService limsDbextractConfigService;
    @Autowired
    @Lazy
    private DbHelper dbHelper;

    @Override
    @SuppressWarnings("unchecked")
    public LimsDbconnDao getDao() {
        return limsDbconnDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsDbconnBean limsDbconn = jsonWrapper.parseUnique(LimsDbconnBean.class);
        limsDbconn.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsDbconn);
        return limsDbconn.getId();
    }

    @Override
    public String connect(RestJsonWrapperBean wrapper) {
        LimsDbconnBean connBean = wrapper.parseUnique(LimsDbconnBean.class);
        connBean = this.selectById(connBean.getId());
        DbHelper dbHelper = ApplicationContextHelper.getBean(DbHelper.class);
        //先尝试连接
        boolean test = dbHelper.test(connBean);
        if(!test){
            //尝试注入
            test = dbHelper.register(connBean);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("result",test);
        return JSONObject.toJSONString(result);
    }

    @Override
    public List<Map<String, Object>> testSQL(RestJsonWrapperBean wrapper) {
        Map<String, String> paramMap = wrapper.getParamMap();
        String dbconnectId = paramMap.get("dbconnectId");
        String sqlId = paramMap.get("sqlId");
        if(ObjectUtils.isEmpty(dbconnectId) || ObjectUtils.isEmpty(sqlId)){
            throw new InvalidDataException("参数异常！");
        }
        LimsDbconnBean limsDbconnBean = this.selectById(Long.parseLong(dbconnectId));
        LimsDbextractConfigBean dbextractConfigBean = limsDbextractConfigService.selectById(Long.parseLong(sqlId));
        String sql = dbextractConfigBean.getSql();
        if(ObjectUtils.isEmpty(sql)){
            throw new InvalidDataException("sql不能为空！");
        }
        Map<String,Object> param = new HashMap<>();
        paramMap.forEach((key,value)->{
            if(key.startsWith("arg:")){
                String field = key.substring(4);
                param.put(field,value);
            }
        });
        List<String> paramMustFit = StringUtils.substringsBetween(sql, "#{", "}");
        for (String s : paramMustFit) {
            if(!param.containsKey(s)){
                throw new InvalidDataException("请输入参数【"+s+"】的值");
            }
        }
        String replaceSql = StringUtils.replaceBetween(sql, "#{", "}",param);
        List<Map<String, Object>> mapList = dbHelper.query(limsDbconnBean, replaceSql);
        //只是测试，最多只返回10条
        if(mapList!=null && mapList.size()>10){
            return mapList.subList(0,10);
        }
        return mapList;
    }
}
